package org.linlinjava.litemall.admin.service;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.SHOP_NOT_ALLOW_DELETE;

import java.math.BigDecimal;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.shiro.SecurityUtils;
import org.linlinjava.litemall.admin.beans.Constants;
import org.linlinjava.litemall.admin.beans.dto.ShopBindErpCodeDto;
import org.linlinjava.litemall.admin.beans.dto.ShopDto;
import org.linlinjava.litemall.admin.beans.enums.AdminOrderStatusEnum;
import org.linlinjava.litemall.admin.beans.pojo.convert.BeanConvert;
import org.linlinjava.litemall.admin.beans.vo.RegionVo;
import org.linlinjava.litemall.admin.beans.vo.ShopVo;
import org.linlinjava.litemall.admin.controller.shop.vo.AdminShopPageReqVO;
import org.linlinjava.litemall.admin.controller.shop.vo.AdminShopPageRespVO;
import org.linlinjava.litemall.admin.util.AdminResponseEnum;
import org.linlinjava.litemall.admin.util.DateUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallAdminOrder;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.domain.LitemallGoodsProduct;
import org.linlinjava.litemall.db.domain.LitemallGoodsRegion;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallRegion;
import org.linlinjava.litemall.db.domain.LitemallShop;
import org.linlinjava.litemall.db.domain.LitemallShopLog;
import org.linlinjava.litemall.db.domain.LitemallShopRegion;
import org.linlinjava.litemall.db.dto.AdminShopSpecialDateDTO;
import org.linlinjava.litemall.db.service.LitemallAdminOrderService;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.service.LitemallGoodsProductService;
import org.linlinjava.litemall.db.service.LitemallGoodsRegionService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.service.LitemallRegionService;
import org.linlinjava.litemall.db.service.LitemallShopLogService;
import org.linlinjava.litemall.db.service.LitemallShopRegionService;
import org.linlinjava.litemall.db.service.LitemallShopService;
import org.linlinjava.litemall.db.util.BeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;


@Service
public class ShopService {

    @Autowired
    private LitemallShopService litemallShopService;

    @Autowired
    private LitemallAdminService litemallAdminService;

    @Autowired
    private LitemallShopLogService litemallShopLogService;

    @Autowired
    private LitemallOrderService litemallOrderService;

    @Autowired
    private LitemallGoodsService litemallGoodsService;

    @Autowired
    private LitemallAdminOrderService litemallAdminOrderService;

    @Autowired
    private LitemallShopRegionService litemallShopRegionService;

    @Autowired
    private LitemallRegionService litemallRegionService;

    @Autowired
    private LitemallGoodsProductService litemallGoodsProductService;

    @Autowired
    private LitemallGoodsRegionService litemallGoodsRegionService;

    @Autowired
    private LitemallRegionService regionService;

    public IPage<AdminShopPageRespVO> page(AdminShopPageReqVO pageReqVO) {
        Short sp = Optional.ofNullable(pageReqVO.getStatus()).map(Integer::shortValue).orElse(null);

        // 构建基础查询条件
        LambdaQueryWrapper<LitemallShop> queryWrapper = Wrappers.lambdaQuery(LitemallShop.class)
                .like(StringUtils.hasText(pageReqVO.getName()), LitemallShop::getName, pageReqVO.getName())
                .like(StringUtils.hasText(pageReqVO.getAddress()), LitemallShop::getStreetAddress, pageReqVO.getAddress())
                .eq(sp != null, LitemallShop::getStatus, sp)
                .between(StringUtils.hasText(pageReqVO.getAddTimeFrom()) && StringUtils.hasText(pageReqVO.getAddTimeTo()),
                        LitemallShop::getAddTime, DateUtil.stringToDate(pageReqVO.getAddTimeFrom()), DateUtil.stringToDate(pageReqVO.getAddTimeTo()));

        // regionId/shopId过滤逻辑
        if (pageReqVO.getRegionId() != null) {
            List<Integer> shopIds = Optional.ofNullable(litemallShopRegionService.queryByRegionId(pageReqVO.getRegionId()))
                    .orElse(Collections.emptyList())
                    .stream()
                    .map(LitemallShopRegion::getShopId)
                    .collect(Collectors.toList());
            if (shopIds.isEmpty()) {
                return new Page<>(0,0);
            }
            queryWrapper.in(LitemallShop::getId, shopIds);
        } else if (pageReqVO.getShopId() != null) {
            queryWrapper.eq(LitemallShop::getId, pageReqVO.getShopId());
        }

        Page<LitemallShop> shopPage = litemallShopService.selectShopPage(queryWrapper, pageReqVO.getPage(), pageReqVO.getLimit());
        IPage<AdminShopPageRespVO> adminShopPageRespPage = BeanUtil.copyPage(shopPage, AdminShopPageRespVO.class);
        adminShopPageRespPage.getRecords().forEach(item->{
            List<LitemallAdmin> adminList = litemallAdminService.findByShopId(item.getId());
            List<LitemallRegion> regionList = Optional.ofNullable(litemallShopRegionService.queryByShopId(item.getId()))
                    .orElse(Collections.emptyList()).stream()
                    .map(LitemallShopRegion::getRegionId)
                    .map(litemallRegionService::findById)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            item.setMembers(adminList.size());
            item.setRegions(CollUtil.reverse(regionList));
            adminList.forEach(admin -> {
                if(Arrays.asList(admin.getRoleIds()).contains(Constants.SHOPKEEPER_ROLE_ID)){
                    item.setShopkeeper(admin.getNickName());
                }
            });
        });
        return adminShopPageRespPage;
    }

    /**
     * 查询商店区域
     * 查询店铺的区域
     *
     * @param shopId 店铺id
     * @return {@link List}<{@link LitemallRegion}>
     */
    public List<LitemallRegion> queryShopRegions(Integer shopId){
    	//区域信息
        List<LitemallShopRegion> regions = litemallShopRegionService.queryByShopId(shopId);
        return litemallRegionService.findByIds(regions.stream().map(LitemallShopRegion::getRegionId).collect(Collectors.toList()));
    }

    /**
     * 细节
     *
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object detail(Integer shopId){
        //门店信息
        LitemallShop litemallShop = litemallShopService.findById(shopId);
        //查询门店人员信息
        List<LitemallAdmin> byShopId = litemallAdminService.findByShopId(litemallShop.getId());
        //区域信息
        List<LitemallShopRegion> regions = litemallShopRegionService.queryByShopId(litemallShop.getId());
        List<LitemallRegion> rs = litemallRegionService.findByIds(regions.stream().map(LitemallShopRegion::getRegionId).collect(Collectors.toList()));
        return ResponseUtil.ok(BeanConvert.toShopVo(litemallShop, byShopId, rs));
    }

    /**
     * 删除
     *
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object delete(Integer shopId){
        if(litemallGoodsService.count(shopId) > 0){
            return ResponseUtil.fail(SHOP_NOT_ALLOW_DELETE, "门店有商品不允许删除");
        }
        litemallShopService.deleteById(shopId);
        //保存日志
        LitemallShop shop = litemallShopService.findById(shopId);
        saveShopLog(Constants.DELETE_MANAGER+shop.getName(), shop);
        return ResponseUtil.ok();
    }

    /**
     * 创建
     *
     * @param shop 商店
     * @return {@link Object}
     */
    @Transactional(rollbackFor = Exception.class)
    public Object create(ShopDto shop){
        if(!StringUtils.isEmpty(shop.getLitemallShop().getName())){
            if(litemallShopService.countByName(shop.getLitemallShop().getName(),null) > 0){
                return ResponseUtil.fail(AdminResponseEnum.SHOP_NAME_EXIST);
            };
        }
        if(!StringUtils.isEmpty(shop.getLitemallShop().getStreetAddress())){
            LitemallShop litemallShop = litemallShopService.countByAddress(shop.getLitemallShop().getStreetAddress(), null);
            if(litemallShop != null){
                //判断区域是否一致
                List<LitemallShopRegion> shopRegions = litemallShopRegionService.queryByRegionIds(shop.getRegionIds());
                if(shopRegions.size() > 0){
                    //区域按门店分组，长度相同则代表存在相同门店
                    boolean anyMatch = shopRegions.stream().collect(Collectors.groupingBy(LitemallShopRegion::getShopId)).entrySet().stream().anyMatch((entry) -> {
                        return entry.getKey() == litemallShop.getId() && entry.getValue().size() == shop.getRegionIds().size();
                    });
                    if(anyMatch){
                        return ResponseUtil.fail(AdminResponseEnum.SHOP_ADDRESS_EXIST);
                    }
                }
            };
        }
        Arrays.sort(shop.getLitemallShop().getTypes());
        litemallShopService.add(shop.getLitemallShop());
        if(shop.getRegionIds() != null){
            for(Integer regionId : shop.getRegionIds()){
                LitemallShopRegion region = new LitemallShopRegion();
                region.setShopId(shop.getLitemallShop().getId());
                region.setRegionId(regionId);
                litemallShopRegionService.add(region);
            }
        }
        //保存日志
        saveShopLog(Constants.CREATE_SHOP+shop.getLitemallShop().getName(), shop.getLitemallShop());

        /**
         * 添加当前用户为店长
         */
        if(null != shop.getShopkeeperId()){
            LitemallAdmin admin = litemallAdminService.findById(shop.getShopkeeperId());
            if(null != admin){
                setShopRole(admin, shop.getShopkeeperId(), shop.getLitemallShop().getId());
            }
        }
        /**
         * 添加当前用户为门店经理
         */
        if(null != shop.getShopManagerId()){
            LitemallAdmin admin = litemallAdminService.findById(shop.getShopManagerId());
            if(null != admin){
                setShopRole(admin, shop.getShopManagerId(), shop.getLitemallShop().getId());
            }
        }

        /**
         * 添加默认商品价格
         */
        List<LitemallGoods> litemallGoods = litemallGoodsService.queryHead();
        for(LitemallGoods goods : litemallGoods){
            LitemallGoodsProduct product = new LitemallGoodsProduct();
            product.setShopId(shop.getLitemallShop().getId());
            product.setGoodsId(goods.getId());
            product.setUnit(goods.getUnit());
            product.setSellPrice(goods.getRetailPrice());
            product.setCostPrice(goods.getCounterPrice());
            litemallGoodsProductService.add(product);
        }
        return ResponseUtil.ok();
    }

    /**
     * 更新
     * 修改门店信息
     *
     * @param shop 商店
     * @return {@link Object}
     */
    @Transactional(rollbackFor = Exception.class)
    public Object update(ShopDto shop) {
        if(!StringUtils.isEmpty(shop.getLitemallShop().getName())){
            if(litemallShopService.countByName(shop.getLitemallShop().getName(),shop.getLitemallShop().getId()) > 1){
                return ResponseUtil.fail(AdminResponseEnum.SHOP_NAME_EXIST);
            };
        }
        if(!StringUtils.isEmpty(shop.getLitemallShop().getStreetAddress())){
            LitemallShop litemallShop = litemallShopService.countByAddress(shop.getLitemallShop().getStreetAddress(), shop.getLitemallShop().getId());
            if(litemallShop != null){
                //判断区域是否一致
                List<LitemallShopRegion> shopRegions = litemallShopRegionService.queryByRegionIds(shop.getRegionIds());
                if(shopRegions.size() > 0){
                    //区域按门店分组，长度相同则代表存在相同门店
                    boolean anyMatch = shopRegions.stream().collect(Collectors.groupingBy(LitemallShopRegion::getShopId)).entrySet().stream().anyMatch((entry) -> {
                        //这里需要判断是否是待修改的门店
                        return entry.getKey() != shop.getLitemallShop().getId() && (litemallShop.getId() == entry.getKey() && entry.getValue().size() == shop.getRegionIds().size());
                    });
                    if(anyMatch){
                        return ResponseUtil.fail(AdminResponseEnum.SHOP_ADDRESS_EXIST);
                    }
                }
            };
        }

        //删除位置信息
        litemallShopRegionService.deletedByShopId(shop.getLitemallShop().getId());
        //添加位置信息
  		Integer countryId = null;
  		Integer provinceId = null;
  		Integer cityId = null;
        if(shop.getRegionIds() != null){
            for(Integer regionId : shop.getRegionIds()){
                LitemallShopRegion region = new LitemallShopRegion();
                region.setShopId(shop.getLitemallShop().getId());
                region.setRegionId(regionId);
                litemallShopRegionService.add(region);

                //查询
                LitemallRegion litemallRegion = litemallRegionService.findById(regionId);
  				Byte regionType = litemallRegion.getType();
  				if(Constants.REGION_TYPE_COUNTRY == regionType) {
  					countryId = regionId;
  				}else if(Constants.REGION_TYPE_PROVINCE == regionType) {
  					provinceId = regionId;
  				}else if(Constants.REGION_TYPE_CITY == regionType){
  					cityId = regionId;
  				}
            }
        }

        //更新门店商品的区域
        List<LitemallGoods> goodsLs = litemallGoodsService.queryShopGoods(shop.getLitemallShop().getId());
        if(!CollectionUtils.isEmpty(goodsLs)) {
        	for (LitemallGoods litemallGoods : goodsLs) {
        		Integer goodsId = litemallGoods.getId();
        		List<LitemallGoodsRegion> result = litemallGoodsRegionService.queryByGid(goodsId);
        		if(!CollectionUtils.isEmpty(goodsLs) && result.size() > 0) {
        			LitemallGoodsRegion goodsRegion = result.get(0);
        			goodsRegion.setCountryId(countryId);
        			goodsRegion.setProvinceId(provinceId);
        			goodsRegion.setCityId(cityId);
        			goodsRegion.setTaxTypes(new Integer[0]);
        			litemallGoodsRegionService.updateById(goodsRegion);
        		}
			}
        }
        //更新门店营业状态
        shop.getLitemallShop().setStatus((short) (shopCheckWeeksTime(shop.getLitemallShop())?1:2));
        litemallShopService.updateById(shop.getLitemallShop());
        //保存日志
        saveShopLog(Constants.UPDATE_SHOP+shop.getLitemallShop().getName(), shop.getLitemallShop());
        if (null != shop.getShopkeeperId() || null != shop.getShopManagerId()) {
            List<LitemallAdmin> admins = litemallAdminService.findByShopId(shop.getLitemallShop().getId());
            //判断店长是否修改
            Boolean updateShopkeeper = admins.stream().anyMatch(admin ->
                 shop.getShopkeeperId() == admin.getId() &&
                    Arrays.asList(admin.getRoleIds()).contains(Constants.SHOPKEEPER_ROLE_ID)
            );
            //判断门店经理是否修改
            Boolean updateShopManager = admins.stream().anyMatch(admin ->
                    shop.getShopManagerId() == admin.getId()&&
                            Arrays.asList(admin.getRoleIds()).contains(Constants.SHOP_MANAGER_ROLE_ID)
            );
           /* if(!updateShopkeeper && null != shop.getShopkeeperId()){
                admins.forEach(admin -> {
                    *//**
                     * 修改旧的门店店长为普通门店用户
                     *//*
                    updateShopRole(admin, Constants.SHOPKEEPER_ROLE_ID, shop.getLitemallShop());
                    *//**
                     * 添加当前用户为店长
                     *//*
                    if(shop.getShopkeeperId() == admin.getId()){
                        setShopRole(admin, Constants.SHOPKEEPER_ROLE_ID, shop.getLitemallShop().getId());
                        //保存日志
                        saveShopLog(Constants.ADD_SHOPKEEPER+admin.getUsername(), shop.getLitemallShop());
                    }
                });
            }*/
            if(!updateShopManager && null != shop.getShopManagerId()){
                admins.forEach(admin -> {
                    /**
                     * 修改旧的门店经理为普通门店用户
                     */
                    updateShopRole(admin, Constants.SHOP_MANAGER_ROLE_ID, shop.getLitemallShop());
                    /**
                     * 添加当前用户为门店经理
                     */
                    if(shop.getShopManagerId() == admin.getId()){
                        setShopRole(admin, Constants.SHOP_MANAGER_ROLE_ID, shop.getLitemallShop().getId());
                        //保存日志
                        saveShopLog(Constants.ADD_MANAGER+admin.getUsername(), shop.getLitemallShop());
                    }
                });
            }

        }

        return ResponseUtil.ok();
    }


    private boolean shopCheckWeeksTime(LitemallShop shop){
        // 假设门店的营业时间已经存在于 shop.getWeeksTime() 集合中
        List<LocalTime[]> weeksTime = shop.getWeeksTime();
        if(weeksTime==null){return false;}
        // 获取当前日期和时间
        LocalDate currentDate = LocalDate.now();
        LocalTime currentTime = LocalTime.now();

        if(StrUtil.isNotEmpty(shop.getTimezone())){
            // 设置选择的时区
            ZoneId zoneId = ZoneId.of(shop.getTimezone());
            // 获取当前日期
            currentDate = LocalDate.now(zoneId);
            // 获取当前时间
            currentTime = LocalTime.now(zoneId);
        }
        // 获取当前是星期几
        DayOfWeek currentDayOfWeek = currentDate.getDayOfWeek();

        // 获取对应的门店营业时间
        LocalTime[] businessHours = weeksTime.get(currentDayOfWeek.getValue() - 1);

        // 判断当前时间是否处于门店的开业时间范围内
        boolean isOpen = currentTime.isAfter(businessHours[0]) && currentTime.isBefore(businessHours[1]);

        List<AdminShopSpecialDateDTO> specialDateList = shop.getSpecial(); // 假设您已经有了AdminShopSpecialDateDTO的集合
        LocalDate today = LocalDate.now();
        // 遍历集合中的每个AdminShopSpecialDateDTO对象
        for (AdminShopSpecialDateDTO dto : specialDateList) {
            LocalDate specialDate = dto.getSpecialDate();
            LocalTime[] specialTime = dto.getSpecialTime();

            // 在这里进行特定逻辑处理，判断门店是否营业
            // 判断specialDate是否是今天
            if (!specialDate.isEqual(today)) {
                continue;
            }
            // 判断当前时间是否在营业时间范围内
            isOpen = currentTime.isAfter(specialTime[0]) && currentTime.isBefore(specialTime[1]);
        }
        return isOpen;
    }


    /**
     * 这位商店商品信息
     * 查询门店商品信息 销售情况 订单情况  商品情况
     *
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object querShopGoodsInfo(Integer shopId){

        Map<String, Object> map = Maps.newHashMap();
        //今日销售
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime todayEnd = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天零点
        map.put("todayAmount", getSalesAmount(shopId, todayStart, todayEnd));
        //最近7天内销售
        LocalDateTime sevenStart = LocalDateTime.of(LocalDate.now().minusDays(7), LocalTime.MIN);
        LocalDateTime sevenEnd = LocalDateTime.of(LocalDate.now().minusDays(1), LocalTime.MAX);
        System.out.println(sevenStart+" "+sevenEnd);
        map.put("sevenAmount", getSalesAmount(shopId, sevenStart, sevenEnd));
        //历史总销售额
        map.put("allAmount", getSalesAmount(shopId, null, null));
        //今日订单数量
        List<LitemallOrder> todayOrders = litemallOrderService.querShopGoodsSalesInfo(shopId, todayStart, todayEnd);
        map.put("todayCount", !CollectionUtils.isEmpty(todayOrders)?todayOrders.size():0);
        //正在进行的订单
        List<LitemallOrder> sevenOrder = litemallOrderService.querNotCompletedOrder(shopId, todayStart, todayEnd);
        map.put("sevenCount", !CollectionUtils.isEmpty(sevenOrder)?sevenOrder.size():0);
        //历史总订单
        List<LitemallOrder> allOrder = litemallOrderService.querShopGoodsSalesInfo(shopId, null, null);
        map.put("allCount", !CollectionUtils.isEmpty(allOrder)?allOrder.size():0);
        //总上架商品
        List<LitemallGoods> litemallGoods = litemallGoodsService.queryPutOnSale(shopId);
        map.put("putOnSaleGoods", !CollectionUtils.isEmpty(litemallGoods)?litemallGoods.size():0);
        //待处理进货请求
        List<Byte> statusList = new ArrayList<>(Arrays.asList(new Byte[]{AdminOrderStatusEnum.P_1.getCode().byteValue(), AdminOrderStatusEnum.P_2.getCode().byteValue(), AdminOrderStatusEnum.P_3.getCode().byteValue(), AdminOrderStatusEnum.P_4.getCode().byteValue()}));
        Long processingCount = litemallAdminOrderService.countProcessingByShopId(shopId, statusList);
        map.put("processingCount", processingCount);
        //该门店的总进货金额
        List<LitemallAdminOrder> litemallAdminOrders = litemallAdminOrderService.merchandiseTotalAmount(shopId, AdminOrderStatusEnum.P_5.getCode().byteValue());
        BigDecimal totalAmount = new BigDecimal(0.0);
        for(LitemallAdminOrder order : litemallAdminOrders){
            totalAmount = totalAmount.add(order.getActualPrice());
        }
        map.put("merchandiseTotalAmount", totalAmount);

        return map;
    }

    /**
     * 得到销售金额
     *
     * @param shopId     商店id
     * @param todayStart 今天开始
     * @param todayEnd   今天结束
     * @return {@link Double}
     */
    private Double getSalesAmount(Integer shopId, LocalDateTime todayStart, LocalDateTime todayEnd) {
        List<LitemallOrder> litemallOrders = litemallOrderService.querShopGoodsSalesInfo(shopId, todayStart, todayEnd);
        if(!CollectionUtils.isEmpty(litemallOrders)){
            return litemallOrders.stream().mapToDouble(orders->Double.valueOf(orders.getActualPrice().toString())).sum();
        }
        return 0d;
    }

    /**
     * 更新商店作用
     * 修改用户为普通门店用户
     *
     * @param admin 管理
     * @param role  角色
     * @param shop  商店
     */
    public void updateShopRole(LitemallAdmin admin, Integer role, LitemallShop shop) {
        if (Arrays.asList(admin.getRoleIds()).contains(role)) {
            LitemallAdmin update = admin;
            update.setRoleIds(Iterables.toArray(Arrays.stream(admin.getRoleIds()).filter(roleId ->
                    role != roleId).collect(Collectors.toList()), Integer.class));

            List<Integer> roleIds = new ArrayList(Arrays.asList(update.getRoleIds()));
            roleIds.add(Constants.SHOP_ASSISTANT_ROLE_ID);
            update.setRoleIds(Iterables.toArray(roleIds, Integer.class));
            litemallAdminService.updateById(update);

            //保存日志
            saveShopLog(Constants.UPDATE_PERMISSION+admin.getUsername(), shop);
        }
    }

    /**
     * 保存商店日志
     *
     * @param context 上下文
     * @param shop    商店
     */
    private void saveShopLog(String context, LitemallShop shop) {
        LitemallAdmin litemallAdmin = (LitemallAdmin) SecurityUtils.getSubject().getPrincipal();
        LitemallShopLog litemallShopLog = new LitemallShopLog();
        litemallShopLog.setCreateUserId(litemallAdmin.getId());
        litemallShopLog.setCreateUserName(litemallAdmin.getUsername());
        litemallShopLog.setIpAddr(litemallAdmin.getLastLoginIp());
        litemallShopLog.setContent(context);
        litemallShopLog.setShopId(shop.getId());
        litemallShopLog.setShopName(shop.getName());
        litemallShopLogService.add(litemallShopLog);
    }

    /**
     * 设置商店作用
     *
     * @param admin  管理
     * @param role   角色
     * @param shopId 商店id
     */
    public void setShopRole(LitemallAdmin admin, Integer role, Integer shopId) {
        List<Integer> roleIds = new ArrayList<>(Arrays.asList(admin.getRoleIds()));
        roleIds.add(role);
        roleIds = roleIds.stream().distinct().collect(Collectors.toList());
        admin.setRoleIds(Iterables.toArray(roleIds, Integer.class));
        admin.setShopId(shopId);
        litemallAdminService.updateById(admin);
    }

    /**
     * 所有
     *
     * @param id id
     * @return {@link List}<{@link LitemallShop}>
     */
    public List<LitemallShop> all(Integer id) {
        if(null != id){
            ArrayList<LitemallShop> rtn = new ArrayList<>();
            rtn.add(litemallShopService.findById(id));
            return rtn;
        }
        return litemallShopService.all();
    }

    /**
     * 查询商店运维
     *
     * @param id id
     * @return {@link Object}
     */
    public Object queryShopOps(Integer id) {
        if(id != null){
            List<LitemallShop> rtn = new ArrayList<>();
            rtn.add(litemallShopService.findById(id));
            return ResponseUtil.ok(rtn);
        }else{
            return ResponseUtil.ok(litemallShopService.all());
        }
    }

    /**
     * 结合erp代码
     *
     * @param shopBindErpCodeDto 商店结合erp代码dto
     * @return {@link Object}
     */
    public Object bindErpCode(ShopBindErpCodeDto shopBindErpCodeDto) {
    	Integer id = shopBindErpCodeDto.getShopId();
    	String erpCode = shopBindErpCodeDto.getErpCode();

    	List<LitemallShop> shops = litemallShopService.queryByErpCode(erpCode);
    	if(null != shops && !shops.isEmpty() && !id.equals(shops.get(0).getId())) {
    		return ResponseUtil.fail(AdminResponseEnum.SHOP_ERP_CODE_EXIST.getCode(), AdminResponseEnum.SHOP_ERP_CODE_EXIST.getMsg());
    	}

    	LitemallShop shop = litemallShopService.findById(id);
    	shop.setErpCode(erpCode);
    	litemallShopService.updateById(shop);

    	//保存日志
        saveShopLog(Constants.BIND_ERPCODE + erpCode, shop);

    	return ResponseUtil.ok();
    }

    /**
     * 复制
     *
     * @param id id
     * @return {@link Object}
     */
    public Object copy(Integer id) {
    	//门店信息
        LitemallShop originShop = litemallShopService.findById(id);
        if(null == originShop) {
        	return ResponseUtil.fail(AdminResponseEnum.COPY_SHOP_NOT_EXIST.getCode(), AdminResponseEnum.COPY_SHOP_NOT_EXIST.getMsg());
        }

    	LitemallShop shop = new LitemallShop();
    	BeanUtils.copyProperties(originShop, shop);
    	shop.setStreetAddress(null);
    	shop.setRange(null);
    	shop.setLongitude(null);
    	shop.setLatitude(null);
    	shop.setErpCode(null);
//    	shop.getTypes().
        Arrays.sort(shop.getTypes());
    	litemallShopService.add(shop);

    	//保存日志
        saveShopLog(Constants.COPY_SHOP + shop.getName(), shop);

    	return ResponseUtil.ok(BeanConvert.toShopVo(shop, new ArrayList<>(), null));
    }

    /**
     * 位置
     *
     * @return {@link Object}
     */
    public Object locations() {
        List<LitemallRegion> countryList = regionService.queryByPid(0);

        //查询的所有的国家
        List<RegionVo> countryVoList = countryList.stream().map(country -> {
            return getRegionVo(country);
        }).collect(Collectors.toList());

        //循环国家找到对应的省份加入到children
        countryVoList = countryVoList.stream().map(country -> {
            List<LitemallRegion> provinceList = regionService.queryByPid(country.getId());
            List<RegionVo> provinceVos = new ArrayList<>();

            //循环根据国家id查询到的省份集合,封装成RegionVo
            provinceVos = provinceList.stream().map(province -> {
                List<LitemallRegion> cityList = regionService.queryByPid(province.getId());

                //循环根据省份id查询到的城市集合,封装成RegionVo
                List<RegionVo> cityVoList = cityList.stream().map(city -> {
                    RegionVo v = getRegionVo(city);

//                    List<LitemallShopRegion> regions = litemallShopRegionService.queryByRegionId(city.getId());
//
//                    List<Integer> shopIds = new ArrayList<>();
//                    shopIds = regions.stream().map(region -> {
//                        return region.getShopId();
//                    }).collect(Collectors.toList());

//                    List<LitemallShop> shops = new ArrayList<>();
//                    if(shopIds.size() > 0){
//                        shops =  litemallShopService.selectByShopIds(shopIds);
//                    }

//                    List<RegionVo> shopRegions =  shops.stream().map( shop ->{
//                        return getShopVo(shop);
//                    }  ).collect(Collectors.toList());

//                    v.setChildren(shopRegions);
                    return v;
                }).collect(Collectors.toList());
                RegionVo vo = getRegionVo(province);
                vo.setChildren(cityVoList);
                return vo;
            }).collect(Collectors.toList());

            country.setChildren(provinceVos);
            return country;
        }).collect(Collectors.toList());
        return ResponseUtil.okList(countryVoList);
    }


    /**
     * 得到地区签证官
     *
     * @param region 地区
     * @return {@link RegionVo}
     */
    public RegionVo getRegionVo(LitemallRegion region){
        RegionVo regionVo = new RegionVo();
        regionVo.setId(region.getId());
        regionVo.setCode(region.getCode());
        regionVo.setNameCn(region.getNameCn());
        regionVo.setNameEn(region.getNameEn());
        regionVo.setType(region.getType());
        regionVo.setPid(region.getPid());
        return regionVo;
    }

    /**
     * 让商店签证官
     *
     * @param shop 商店
     * @return {@link RegionVo}
     */
    public RegionVo getShopVo(LitemallShop shop){
        RegionVo regionVo = new RegionVo();
        regionVo.setId(shop.getId());
        regionVo.setNameCn(shop.getName());
        regionVo.setNameEn(shop.getName());
        return regionVo;
    }
}
